package inutan.gateway.session;

import inutan.common.constant.DataConstant;
import inutan.common.inner.protocol.InnerMessage;
import inutan.gateway.session.user.UserSession;
import org.ricks.ioc.RicksContext;
import org.ricks.ioc.definition.wrap.ActionMethodWrapper;
import org.ricks.net.AioSession;
import org.ricks.net.DataCodecKit;
import org.ricks.net.NetContext;
import org.ricks.net.Router;
import org.ricks.net.rpc.AskPackage;
import org.ricks.net.rpc.Consumer;
import org.ricks.protocol.ByteBuf;
import org.ricks.protocol.ProtocolManager;

import java.util.*;

/**
 * @author chenwei
 * @Description: session 统一管理，不管外部 还是 内部
 * @date 2023/2/917:09
 */
public class LogicSessions {

    public static LogicSessions me() {
        return Holder.ME;
    }

    /** 通过 JVM 的类加载机制, 保证只加载一次 (singleton) */
    private static class Holder {
        static final LogicSessions ME = new LogicSessions();
    }


    public void route(InnerMessage msg, UserSession userSession) {
        msg.setRoomMap(userSession.getRoomMap());
        ActionMethodWrapper actionMethodWrapper = RicksContext.me().getActionMethod(msg.cmd);
        byte moduleId = actionMethodWrapper.getModuleId();
        AioSession logicSession = userSession.getLogicSession(moduleId);
        /**
         * UserSession绑定了内部逻辑模块Session
         */
        if(Objects.nonNull(logicSession)) {
            logicSession.send(msg);
            return;
        }
        Consumer.me().send(msg.cmd, msg, userSession.getUserId());
    }

    public void syncAsk(InnerMessage msg, UserSession userSession, java.util.function.Consumer<AskPackage> consumer) {
        ActionMethodWrapper actionMethodWrapper = RicksContext.me().getActionMethod(msg.cmd);
        byte moduleId = actionMethodWrapper.getModuleId();
        AioSession logicSession = userSession.getLogicSession(moduleId);
        /**
         * UserSession绑定了内部逻辑模块Session
         */
        if(Objects.nonNull(logicSession)) {
            ByteBuf buf = new ByteBuf(1024);
            ProtocolManager.write(buf, msg);
            byte[] bytes = buf.toArray();
            Router.me().syncAsk(logicSession,msg.cmd, bytes, consumer );
        }
    }

}
